package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"runtime"
	"runtime/debug"
	"strings"
)

func init() {
	log.SetPrefix("TRACE: ")
	log.SetFlags(log.Ldate | log.Lmicroseconds | log.Llongfile)
}

type Http struct {
	Host string
}

func (h *Http) Get(url string) string {
	debug.PrintStack()
	res, err := http.Get(url)
	defer res.Body.Close()
	if err != nil {
		log.Println(err)
		return ""
	}
	body, _ := ioutil.ReadAll(res.Body)
	a, _ := Get("Hello")
	log.Printf(a)
	return string(body)
}

func getStack() string {
	buf := make([]byte, 1024)
	runtime.Stack(buf, false)
	return string(buf)
}

func loadTemplate() string {
	t := template.Must(template.ParseFiles("templates/simple.html"))
	book := &Book{}
	var b bytes.Buffer
	t.Execute(&b, book)
	return string(b.Bytes())
}

type Chapter struct {
	Href    string
	Title   string
	SortNo  int
	Content string

	Children []Chapter

	Book Book
}

type Book struct {
	Host      string
	Isbn      string
	SourceUrl string
	Title     string
	CoverUrl  string
	Cat       string
	Tags      []string
	Author    string
	Authors   []string

	Chapters []Chapter
}

type Site struct {
	Host    string `json:"host"`
	ItemUrl string `json:"itemUrl"`
	PageUrl string `json:"pageUrl"`
	Code    string `json:"code"`
	Slugs   string `json:"slugs"`
}
type CmdOption struct {
	BookId        string `json:"bookId"`
	Target        string `json:"target"`
	SiteName      string `json:"siteName"`
	Site          Site   `json:"site"`
	CacheProvider string `json:"cacheProvider"`
	StartPage     int    `json:"startPage"`
	EndPage       int    `json:"endPage"`
}

func (co CmdOption) composeUrl() ([]string, bool) {
	pageMode := false
	urlList := []string{}
	if co.BookId != "" {
		idList := strings.Split(co.BookId, ",")
		if len(idList) != 0 {
			for item := range idList {
				urlList = append(urlList, fmt.Sprintf(co.Site.ItemUrl, idList[item]))
			}
		}
	}
	if len(urlList) > 0 {
		pageMode = false
	} else {
		pageMode = true

		for i := co.StartPage; i <= co.EndPage; i++ {
			urlList = append(urlList, fmt.Sprintf(co.Site.PageUrl, i))
		}
	}

	return urlList, pageMode
}
func (co CmdOption) getHost() string {
	return co.Site.Host
}
func (co *CmdOption) parseHost() {
	if co.SiteName == "h" || co.SiteName == "hetushu" {
		co.Site = Site{
			Code:    "hetushu",
			ItemUrl: "http://www.hetushu.com/book/%s/index.html",
			PageUrl: "http://www.hetushu.com/book/index.php?page=%d&state=2",
			Slugs:   "hetushu,h,",
		}
	} else if co.SiteName == "9" || co.SiteName == "99lib" {
		co.Site = Site{
			Code:    "99lib",
			ItemUrl: "http://www.99lib.net/book/%s/index.htm",
			PageUrl: "",
			Slugs:   "99lib,9,",
		}
	} else {

	}
}

func parseCmdOption() CmdOption {
	bookId := flag.String("book_id", "", "Book Id(s) separte by comma when have multiple")
	siteName := flag.String("site_name", "h", "Site Name: hetushu[h],99lib[9] ")
	target := flag.String("target", "epub2", "Target: epub2,epub3,db,txt ")
	cacheProvider := flag.String("cache", "local", "Cache Provider: local, memory, file, dummy")
	startPage := flag.Int("start", 0, "Start Page")
	endPage := flag.Int("end", 0, "End Page")
	flag.Parse()

	co := CmdOption{
		BookId:        *bookId,
		Target:        *target,
		SiteName:      *siteName,
		CacheProvider: *cacheProvider,
		StartPage:     *startPage,
		EndPage:       *endPage,
	}
	return co
}

func jsonEncode(i interface{}) string {
	data, _ := json.Marshal(i)
	return string(data)
}

func main() {
	fmt.Println("Hello")
	ages := []int{1, 2, 3}
	log.Print("Hello", ages)

	co := parseCmdOption()
	//fmt.Println(co)
	//SmartPrint(co)

	fmt.Println(jsonEncode(co))
	co.parseHost()
	fmt.Println(jsonEncode(co))
	fmt.Println(co.composeUrl())
}
